﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data;
using MaxLeaf.Common;
using System.Text;

namespace MaxLeaf.DB
{
    public class K3DBFactory
    {
        public static DbConnection CreateDbConnection(string strConn)
        {
            return new SqlConnection(strConn);
        }

        public static DbDataAdapter CreateDataAdapter(string strSql, DbConnection dbCon)
        {
            return new SqlDataAdapter(strSql, (SqlConnection)dbCon);
        }

        public static string CreateConnectionString(ServerInfo server)
        {
            return string.Format("Data Source={0},{1};Initial Catalog={2};User Id={3};Password={4};"
                        , server.IP
                        , server.Port
                        , server.Database
                        , server.Uid
                        , server.Pwd
                        );
        }

        public static DbCommand CreateCommand( DbConnection dbCon)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = (SqlConnection)dbCon;
            cmd.CommandTimeout = 500;

            return cmd;
        }

        public static KeyValuePair<string, IDataParameter[]> CreateParamSql(string strFieldName, string strTableName, DataRow dr, LogStatus logStatus, string strKeyFieldName)
        {
            string strSql = string.Empty;
            strFieldName = strFieldName.Replace(" ", "");
            strFieldName = strFieldName.Replace("\r", "");
            strFieldName = strFieldName.Replace("\n", "");
            string[] strFieldNames = strFieldName.Split(',');
            System.Collections.Generic.List<SqlParameter> lstParam = new System.Collections.Generic.List<SqlParameter>(strFieldNames.Length);

            if (dr != null)
            {
                #region add mode
                if (logStatus == LogStatus.Add)
                {
                    StringBuilder sbInsert = new StringBuilder("");
                    StringBuilder sbValues = new StringBuilder("");
                    sbInsert.AppendFormat("insert into {0} (", strTableName);
                    sbValues.AppendFormat("values (");
                    for (int i = 0; i < strFieldNames.Length; i++)
                    {
                        if (dr[strFieldNames[i]] != null && dr[strFieldNames[i]] != System.DBNull.Value)
                        {
                            sbInsert.AppendFormat(@"{0},", strFieldNames[i]);
                            sbValues.AppendFormat(@"@{0},", strFieldNames[i]);
                            lstParam.Add(new SqlParameter(string.Format("@{0}", strFieldNames[i]), dr[strFieldNames[i]]));
                        }
                    }
                    string strInsertSql = sbInsert.ToString();
                    int iLast = strInsertSql.LastIndexOf(',');
                    strInsertSql = CvtFunc.ToLeftString(strInsertSql, iLast);
                    strInsertSql += ")";
                    string strValuesSql = sbValues.ToString();
                    iLast = strValuesSql.LastIndexOf(',');
                    strValuesSql = CvtFunc.ToLeftString(strValuesSql, iLast);
                    strValuesSql += ")";

                    strSql = string.Format("{0} \r\n {1} \r\n ;select  @@identity ", strInsertSql, strValuesSql);
                    


                }
                #endregion
                #region update mode
                else if (logStatus == LogStatus.Update)
                {
                    StringBuilder stbSql = new System.Text.StringBuilder("");
                    stbSql.AppendFormat("update  {0} set ", strTableName);
                    for (int i = 0; i < strFieldNames.Length; i++)
                    {
                        if (dr[strFieldNames[i]] != null && dr[strFieldNames[i]] != System.DBNull.Value)
                        {
                            stbSql.AppendFormat(@"{0}=@{0}", strFieldNames[i]);
                            stbSql.AppendLine(",");
                            lstParam.Add(new SqlParameter(string.Format("@{0}", strFieldNames[i]), dr[strFieldNames[i]]));
                        }
                    }
                    strSql = stbSql.ToString();
                    int iLast = strSql.LastIndexOf(',');
                    strSql = CvtFunc.ToLeftString(strSql, iLast);
                    strSql += string.Format(" where {0}=@{0};select 1", strKeyFieldName);
                    lstParam.Add(new SqlParameter(string.Format("@{0}", strKeyFieldName), dr[strKeyFieldName]));


                   

                }
                #endregion

                return new KeyValuePair<string, IDataParameter[]>(strSql, lstParam.ToArray<IDataParameter>());
            }
            return new KeyValuePair<string, IDataParameter[]>(string.Empty, null);
        }

        public static KeyValuePair<string, IDataParameter[]> CreateCondParam(Dictionary<string, object> dictCond)
        {
            List<SqlParameter> lstParam = new List<SqlParameter>();
            string strSql=string.Empty;
            foreach (KeyValuePair<string, object> kvp in dictCond)
            {
                if (strSql.Length == 0)
                {
                    strSql = string.Format("{0}=@{0}",kvp.Key);
                }
                else
                {
                    strSql += string.Format(" and {0}=@{0}", kvp.Key);
                }
                lstParam.Add(new SqlParameter(string.Format("@{0}", kvp.Key), kvp.Value));
            }

            return new KeyValuePair<string, IDataParameter[]>(strSql, lstParam.ToArray<IDataParameter>());
        }
    }
}